﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Xml;

public partial class _Default : System.Web.UI.Page 
{
    protected string _sLinkToGeoRSS;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            //RegisterStartupScript("start", "javascript:load()");

            TwitterUser user = new TwitterUser(Page);
            if (user.UserName == null)
                Response.Redirect("SignIn.aspx");

            GetTimeline();
            GetUser();
            
            _sLinkToGeoRSS = "http://geotwitter.net/georss.aspx?token=" + GeoRSSLibrary.EncryptUtils.Encrypt(user.UserName + " " + user.Password);
        }
    }

    private void GetUser()
    {
        TwitterUser user = new TwitterUser(Page);
        Twitter twitter = new Twitter();

        string sXml = twitter.Show(user.UserName, user.Password, user.UserName, Twitter.OutputFormatType.XML);

        XDocument loaded = XDocument.Parse(sXml);
        var allElements = from stat in loaded.Descendants("user")
                          select new
                          {
                              ID = stat.Element("id").Value,                              
                              UserImage = stat.Element("profile_image_url").Value,
                          };
        foreach (var stat in allElements)
        {
            user.Image = stat.UserImage;
            user.ID = stat.ID;
        }
    }

    private void GetTimeline()
    {
        TwitterUser user = new TwitterUser(Page);
        Twitter twitter = new Twitter();

        //string sXml2 = twitter.GetUserTimeline(user.UserName, user.Password, user.UserName, Twitter.OutputFormatType.XML);
        string sXmlFriends = twitter.GetFriendsTimeline(user.UserName, user.Password, Twitter.OutputFormatType.XML);

        XDocument loaded = XDocument.Parse(sXmlFriends);

        var allElements = from stat in loaded.Descendants("status")
                          select new
                          {
                              Text = stat.Element("text").Value,
                              Name = stat.Element("user").Element("name").Value,
                              UserImage = stat.Element("user").Element("profile_image_url").Value,
                          };

        DataTable dataTable = new DataTable("status");
        dataTable.Columns.Add("text");
        dataTable.Columns.Add("name");
        dataTable.Columns.Add("userimage");
        //dataTable.Columns.Add("reply");

        foreach (var stat in allElements)
        {
            DataRow row = dataTable.NewRow();
            row["userimage"] = stat.UserImage;
            row["name"] = stat.Name;
            row["text"] = stat.Text;
            //row["reply"] = stat.Name;

            dataTable.Rows.Add(row);
        }

        GridView1.DataSource = dataTable;
        GridView1.DataBind();

        // Response Write this:
        /*
         * var groundOverlay = new GGroundOverlay("http://bbs.keyhole.com/ubb/z0302a1700/etna.jpg", new GLatLngBounds(pointSW, pointNE));map.addOverlay(groundOverlay);
         */
    }

    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        if (textPosition.Text.Length == 0)
        {
            LabelError.Text = "Click the map to add your location";
            return;
        }
        if (TextBoxInput.Text.Length == 0)
        {
            LabelError.Text = "Add a message to display";
            return;
        }

        LabelError.Text = "";

        TwitterUser user = new TwitterUser(Page);
        Twitter twitter = new Twitter();

        //http://geotwitter.net/l.aspx?g=3
        //http://maps.google.com/?ie=UTF8&ll=33.898265,-117.318406

        string sLink = " " + System.Configuration.ConfigurationManager.AppSettings["Host"].ToString() + "/l.aspx?g=";
        string [] latLon = textPosition.Text.Replace("(", "").Replace(")","").Replace(" ","").Split(',');

        DataClassesDataContext dd = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["GeoTwitterDataConnectionString"].ConnectionString);
        Link link = new Link();
        link.lat = latLon[0];
        link.lon = latLon[1];
        link.timestamp = DateTime.Now;
        dd.Links.InsertOnSubmit(link);
        dd.SubmitChanges();

        sLink += link.ID;

        string sXml = twitter.Update(user.UserName, user.Password, TextBoxInput.Text + sLink, Twitter.OutputFormatType.XML);

        LastPosition last = new LastPosition();
        last.lat = latLon[0];
        last.lon = latLon[1];
        last.Text = TextBoxInput.Text + sLink;
        last.timestamp = DateTime.Now;
        last.UserName = user.UserName;
        last.UserImage = user.Image;
        last.UserID = user.ID;
        dd.LastPositions.InsertOnSubmit(last);
        dd.SubmitChanges();

        // Update the grid
        GetTimeline();
    }
}
